package com.zx.framework.file.upload.util;

import com.zx.framework.core.util.FileUtil;
import com.zx.framework.file.upload.controller.UploadException;
import com.zx.framework.file.upload.vo.FileCtx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * 文件合并工具
 * Created by FLT on 2015/11/15.
 */
public class FileMergUtil {
    private static Logger LOG = LoggerFactory.getLogger(FileMergUtil.class);
    /**
     * 合并文件
     */
    public static void mergFile(FileCtx fileCtx,String ctxArray) {
        String[] ctxs = ctxArray.split(",");
        File file = fileCtx.getSaveFile();
        for (String ctx : ctxs){
            File chunkFile = fileCtx.getChunk(ctx);
            if (null == chunkFile){
                throw new UploadException("ctx:["+ctx+"] in ctx array can not find file!");
            }
            byte[] chunkByte;
            try {
                chunkByte = FileUtil.readFileToByteArray(chunkFile);
                FileUtil.writeByteArrayToFile(file,chunkByte,true);
            } catch (IOException e) {
                LOG.error("merge file err!", e);
                throw new UploadException("merge file err:"+e.getMessage());
            }
        }
    }
}
